<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="schema" v-slot="{errors}" autocomplete="off">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field name="accountApi" v-model="form.account" class="input" :class="{err:errors.accountApi}" type="text" placeholder="请输入用户名" />
      </div>
       <div v-if="errors.accountApi" class="error">{{errors.accountApi}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field v-model="form.mobile" name="mobile" class="input" :class="{err:errors.mobile}" type="text" placeholder="请输入手机号" />
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field v-model="form.code" name="code" class="input" :class="{err:errors.code}" type="text" placeholder="请输入验证码" />
        <span class="code" @click="send">{{time===0?'发送验证码':time+'秒后发送'}}</span>
      </div>
      <div v-if="errors.code" class="error">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field v-model="form.password" name="password" class="input" :class="{err:errors.password}" type="password" placeholder="请输入密码" />
      </div>
      <div v-if="errors.password" class="error">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field name="rePassword" class="input" :class="{err:errors.rePassword}" type="password" placeholder="请确认密码" />
      </div>
      <div v-if="errors.rePassword" class="error">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" @click="login" class="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { reactive, ref, watch } from 'vue'
import { useIntervalFn } from '@vueuse/shared'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { Message } from '@/components/library/Message'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'CallbackPatch',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 收集用户信息-且用于后续表单校验的对象
    const form = reactive({
      unionId: '',
      account: '',
      mobile: '',
      code: '',
      password: ''
    })
    // 💥由于父组件获取 unionId 是异步的，可通过监听变化获取最新值
    watch(() => props.unionId, (val) => {
      form.unionId = val
    }, { immediate: true })
    // 短信验证
    // 计时器
    const time = ref(0)
    const { resume, pause } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 点击发送验证码
    const formCom = ref(null)
    const send = async () => {
      // 校验手机号，如果成功才去发送短信
      const mobileChecked = schema.mobile(form.mobile)
      if (mobileChecked === true) {
        // 没有倒计时才可以发送
        if (time.value !== 0) return
        // 倒计时重置
        time.value = 60
        // 开始倒计时
        resume()
        // 发送验证码
        try {
          await userQQPatchCode(form.mobile)
          Message({ type: 'success', message: '验证码发送成功' })
        } catch (err) {
          Message({ type: 'error', message: err.response.data.message || '获取验证码出现错误' })
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', mobileChecked)
      }
    }

    // 注册提交
    const store = useStore()
    const router = useRouter()
    const login = async () => {
      // form.unionId = props.unionId
      // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
      const valid = await formCom.value.validate()
      if (!valid) return Message({ type: 'error', message: '表单验证失败' })
      // console.log(router)
      try {
        const { result } = await userQQPatchLogin(form)
        Message({ type: 'success', message: 'QQ完善信息成功' })
        // 1. 存储 token 信息
        store.commit('user/setUser', result)
        // 2. 页面跳转（两种情况：1.回跳到某个页面 2.跳转首页
        // router.currentRoute.value 获取当前路由
        router.push(router.currentRoute.value.query.redirectUrl || '/')
        // 登录成功后合并购物车数据
        store.dispatch('cart/mergeLocalCart')
      } catch (error) {
        console.dir(error)
        Message({ type: 'error', message: error.response.data.message || '完善信息失败' })
      }
    }
    return { schema, form, time, send, formCom, login }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
